package com.zcsy.manage.web.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.mall.OwnerAddress;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.mall.IOwnerAddressService;

@Controller
@RequestMapping(value = "ownerAddress")
public class OwnerAddressController {

	@Autowired
	private IOwnerAddressService ownerAddressService;

	@Autowired
	private ICellHouseService cellHouseService;
	
	@Autowired
	private ICellRegionService cellRegionService;
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	/**
	 * @Description 收货地址进入画面
	 * @return 跳转页面
	 * @author liuying 1075817474@qq.com
	 * @date 2016年8月3日
	 * @see 
	 */
	@RequestMapping(value="ownerAddressList" , method = RequestMethod.GET)
    public String ownerAddressList(Model model,String addressId, HttpServletRequest req){
		
		//获取到当前用户登陆时默认的小区id
        String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
		//获取当前登陆的用户的信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        
		OwnerAddress ownerAddress = new OwnerAddress();
		ownerAddress.setOwnerId(ownerId);
		ownerAddress.setCellId(cellId);
		ownerAddress.setId(addressId);
        List<OwnerAddress> ownerAddressList = ownerAddressService.selectAddressByOwnerIdAndCellId(ownerAddress);
        		
        model.addAttribute("cellRegions", cellRegionService.getCellRegionByCellId(cellId));
        
        //编辑时
        if (addressId != null){
    		OwnerAddress address = ownerAddressService.selectByPrimaryKey(addressId);
    		CellHouse cellHouse = cellHouseService.selectByPrimaryKey(address.getHouseId());
    		
	        model.addAttribute("cellBuildings", cellBuildingService.getCellBuildingByRegionId(cellHouse.getRegionId()));
	    	model.addAttribute("cellUnits", cellUnitService.getCellUnitByBuildingId(cellHouse.getBuildingId()));
	    	model.addAttribute("cellHouses", cellHouseService.getCellHouseByUnitId(cellHouse.getUnitId()));
	    	model.addAttribute("cellHouse", cellHouse);
	    	model.addAttribute("ownerAddress", address);
        }

        //将电话号码中间四位隐藏起来
        String recepientPhone = null;
        for(int i=0; i<ownerAddressList.size(); i++){
        	recepientPhone = ownerAddressList.get(i).getRecepientPhone();
        	if(recepientPhone != null && recepientPhone.length() == 11){
	        	recepientPhone = recepientPhone.substring(0,recepientPhone.length()-(recepientPhone.substring(3)).length())+"****"+recepientPhone.substring(7);
	        	ownerAddressList.get(i).setRecepientPhone(recepientPhone);
        	}
        }
        
		model.addAttribute("ownerAddressList", ownerAddressList);
		model.addAttribute("count", ownerAddressService.selectCountByOwnerIdAndCellId(ownerId, cellId));
        
        return "base/owneraddress/ownerAddress";
    }
	
	/**
	 * @Description 保存或修改收货地址
	 * @param ownerAddress 保存对象
	 * @return 保存结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年8月4日
	 * @see 
	 */
	@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdate(OwnerAddress ownerAddress,HttpServletRequest request) {
        RequestJson result = new RequestJson();
        
        //需要的查询条件
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        String cellId = ((CellInfo) request.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
        CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
		String houseId = ownerAddress.getHouseId();
		CellHouse house = cellHouseService.selectByPrimaryKey(houseId);

		//需要插入的数据
		ownerAddress.setOwnerId(ownerId);
		ownerAddress.setProvinceId(cellInfo.getProvinceId().toString());
		ownerAddress.setCityId(cellInfo.getCityId().toString());
		ownerAddress.setAreaId(cellInfo.getAreaId().toString());
		ownerAddress.setCellId(cellId);
		StringBuffer detailAddress = new StringBuffer();
		detailAddress.append(cellInfo.getProvinceName())
				.append(cellInfo.getCityName()).append(cellInfo.getAreaName())
				.append(cellInfo.getCellName()).append(house.getRegionName())
				.append(house.getBuildingName())
				.append(house.getUnitName()).append(house.getName());
		ownerAddress.setDetailAddress(detailAddress.toString());
		
		//当传入的对象为默认地址且数据库中已有默认地址时
		if(ownerAddress.getDefaultFlag() == 1 && ownerAddressService.selectDefaultFlagCount(ownerId, cellId) >= 1){
			ownerAddressService.updateDefaultFlag(ownerId, cellId);
		}
		
        try {
        	if(ownerAddress.getId() == null || ownerAddress.getId() == ""){
        		ownerAddress.setId(UniqueNumberUtils.get18UniqueNumber());
        		ownerAddressService.insertAddress(ownerAddress);
        	} else {
        		ownerAddressService.updateAddress(ownerAddress);
        	}
        	
			result.setSuccess(true);
			
        }catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        
        return result;
    }
	
	/**
	 * @Description 删除收货地址
	 * @param addressId 收货地址信息id
	 * @return 删除结果 
	 * @author liuying 1075817474@qq.com
	 * @date 2016年8月4日
	 * @see 
	 */
	@RequestMapping(value = "deleteOwnerAddress", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteOwnerAddress(String addressId) {

        RequestJson result = new RequestJson();
        
        try {
			if(addressId != null && addressId != ""){
				
					ownerAddressService.deleteByPrimaryKey(addressId);
					result.setSuccess(true);
			} else {
				result.setSuccess(false);
			}
				
			
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }
	
	/**
	 * @Description 将普通地址设为默认地址
	 * @param addressId 主键id
	 * @return 更新结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年8月8日
	 * @see 
	 */
	@RequestMapping(value = "changeDefault", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson changeDefault(String addressId, HttpServletRequest request) {

        RequestJson result = new RequestJson();
        
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        String cellId = ((CellInfo) request.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
        
        //当传入的对象为默认地址且数据库中已有默认地址时
  		if(ownerAddressService.selectDefaultFlagCount(ownerId, cellId) >= 1){
  			ownerAddressService.updateDefaultFlag(ownerId, cellId);
  		}
  		
  		int flag = ownerAddressService.updateToDefaultAddress(addressId);
  		
  		if(flag == 1){
  			result.setSuccess(true);
  			result.setMsg("成功设为默认地址！");
  		} else {
  			result.setSuccess(true);
  			result.setMsg("设为默认地址失败！");
  		}
  		
        return result;
    }
}
